<!-- 收藏模板 -->
<template>
    <el-dialog
        v-model="showDialog"
        :title="title"
        width="520px"
        append-to-body
        destroy-on-close
        @close="onClose"
    >
        <el-form
            ref="formRef"
            :model="config"
            :rules="rules"
            label-width="90px"
        >
            <el-form-item label="模板名称" prop="title" required>
                <el-input v-model="config.title" placeholder="请选择模板名称" style="width: 240px;"></el-input>
            </el-form-item>
            <el-form-item label="模板分类" prop="categoryId" required>
                <div class="select-wrap">
                    <el-select v-model="config.categoryId" placeholder="请选择模板分类">
                        <el-option
                            v-for="item in templateCategorys"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        >
                        </el-option>
                    </el-select>
                    <div class="add-category-btn" @click="onAddCategory">
                        <el-icon><icon-plus /></el-icon>
                        添加分类
                    </div>
                </div>                
            </el-form-item>
            <el-form-item label="模板缩略图">
                <image-picker
                    v-model="config.cover"
                    :show-label="false"
                    :size="40"
                    type="image"
                />
            </el-form-item>
            <el-form-item label="模板权重">
                <el-input-number
                    v-model="config.sort"
                    :min="1"
                    controls-position="right"
                    style="width: 128px;"
                />
                <div class="tip-txt">
                    注：权重大小将会改变模板的摆放顺序（权重越大越往前）
                </div>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="onCancel">取消</el-button>
                <el-button type="primary" @click="onConfirm">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { defineComponent, toRefs, ref, reactive } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { saveUserTemplate, getUserTemplateCategorys, saveUserTemplateCategory } from '@/api/app'
import bus from '@/libs/bus'
import { randomStr, deepClone } from '@/libs/tools'
export default defineComponent({
    name: 'CollectionTemplate',
    props: {
        // 标题
        title: {
            type: String,
            default: '收藏为组合模块'
        },
        // 模板类型(page单页，comb组合)
        type: {
            type: String,
            default: 'comb'
        }
    },
    setup(props) {
        const { title, type } = toRefs(props)

        const busId = randomStr(16)
        const showDialog = ref(false)
        const templateCategorys = ref([])

        const formRef = ref(null)
        const config = ref({})
        const rules = reactive({
            title: [{
                validator: (rule, value, callback) => !value ? callback(new Error('模板名不能为空')) : true,
                trigger: 'blur'
            }],
            categoryId: [{
                validator: (rule, value, callback) => !value ? callback(new Error('模板分类不能为空')) : true,
                trigger: 'blur'
            }]
        })

        /**
         * 打开弹窗
         * @param {*} title 模板名称
         * @param {*} categoryId 模板分类
         * @param {*} cover 模板缩略图
         * @param {*} data 模板内容
         * @param {*} id 模板ID
         * @param {*} sort 模板权重
         */
        const show = data => {
            config.value = deepClone(data)
            getTemplateCategorys()
            showDialog.value = true
            return new Promise((resolve, reject) => {
                bus.on(`${busId}-confirm`, () => {
                    showDialog.value = false
                    resolve(config.value)
                })
                bus.on(`${busId}-cancel`, () => {
                    showDialog.value = false
                    reject()
                })
            })
        }

        const onClose = () => {
            bus.off(`${busId}-confirm`)
            bus.off(`${busId}-cancel`)
        }

        // 获取模板分类列表
        const getTemplateCategorys = () => {
            getUserTemplateCategorys().then(res => {
                if (res.Status == 1) {
                    templateCategorys.value = res.Data.Data.map(item => ({
                        label: item.Title,
                        value: item.Id
                    }))
                }
            }).catch(err => {
                reject(err)
            })
        }
        // 添加分类
        const onAddCategory = () => {
            ElMessageBox.prompt('请输入分类名', '添加分类', {
                inputValue: '分类名',
                inputValidator: value => value !== '',
                inputErrorMessage: '分类名不能为空',
            }).then(({ value }) => {
                saveUserTemplateCategory({
                    title: value,
                    pId: 0
                }).then(res => {
                    if (res.Status == 1) {
                        ElMessage({
                            type: 'success',
                            message: '添加分类成功'
                        })
                        getTemplateCategorys()
                    } else {
                        ElMessage({
                            type: 'warning',
                            message: '添加分类失败'
                        })
                    }
                })
            }).catch(() => {})
        }

        const onCancel = () => {
            bus.emit(`${busId}-cancel`)
        }
        const onConfirm = () => {
            formRef.value.validate((status, data) => {
                if (status) {
                    saveUserTemplate({
                        type: type.value,
                        categoryId: config.value.categoryId,
                        title: config.value.title,
                        data: JSON.stringify(config.value.data),
                        cover: config.value.cover,
                        sort: config.value.sort,
                        id: config.value.id
                    }).then(res => {
                        if (res.Status == 1) {
                            ElMessage({
                                type: 'success',
                                message: '收藏成功'
                            })
                            bus.emit(`${busId}-confirm`)
                        } else {
                            ElMessage({
                                type: 'warning',
                                message: '收藏失败'
                            })
                        }
                    })
                }
            })
        }

        return {
            title,

            showDialog,
            templateCategorys,
            formRef,
            config,
            rules,

            show,
            onClose,
            onAddCategory,
            onCancel,
            onConfirm
        }
    }
})
</script>

<style lang="less" scoped>
.select-wrap {
    display: flex;
    align-items: center;
    .add-category-btn {
        margin-left: 10px;
        cursor: pointer;
        &:hover {
            color: var(--edit-color-primary);
        }
    }
}
.tip-txt {
    margin-top: 10px;
    color: rgb(159, 165, 187);
    font-size: 12px;
    line-height: 22px;
}
</style>